package com.googlecode.monitoring.dao;

import com.googlecode.monitoring.exception.DataDaoException;
import com.googlecode.monitoring.model.AlertText;
import com.googlecode.monitoring.model.ItemToCheck;
import com.googlecode.monitoring.model.Person;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public abstract class AgentConfigurationDao {

    /**
     * Gets all WsItemToCheck objects
     *
     * @return List of WsItemToCheck objects
     * @throws DataDaoException DataDaoException
     */
    abstract public List<ItemToCheck> getAllItemsFromConfiguration()  throws DataDaoException;

    abstract public AlertText getAlertText() throws DataDaoException;

    abstract public List<Person> getCommonResponsiblePersons();

    public String replacePlaseHoldersInAlertText(Map<String, Object> context, String text) throws DataDaoException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
        Pattern lookupPattern = Pattern.compile("\\{([^\\}]+)\\}");
        int position = 0;
        StringBuffer result = new StringBuffer();

        Matcher m = lookupPattern.matcher(text);
        while (m.find()) {
            result.append(text.substring(position, m.start()));
            result.append(BeanUtils.getNestedProperty(context, m.group(1)));
            position = m.end();
        }

        if (position == 0) {
            return text;
        } else {
            result.append(text.substring(position));
            return result.toString();
        }
    }

}
